package com.example.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.R;
import com.example.domain.User;
import com.example.domain.model.MyPage;
import com.example.domain.model.UserDTO;
import com.example.service.UserService;
import com.example.util.JsonUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;

@Slf4j
@Api(tags = "用户管理（管理员）")
@RestController
@RequestMapping("/admin")
@RequiresPermissions("admin:manage")
public class AdminController {

    @Resource
    private UserService userService;

    @ApiOperation(value = "用户列表")
    @PostMapping("/list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页索引", defaultValue = "1"),
            @ApiImplicitParam(name = "size", value = "每页显示记录数", defaultValue = "20")
    })
    public R<Page<UserDTO>> getList(@RequestBody MyPage myPage){
        Page page = new Page(myPage.getCurrent(), myPage.getSize());
        return R.success(JsonUtil.getJsonToBean(userService.getlist(page), Page.class));
    }
    @ApiOperation(value = "删除")
    @DeleteMapping("/{id}")
    public R delete(@PathVariable String id){
        return userService.delete(id)?R.success():R.error("删除失败");
    }

    @ApiOperation(value = "新增")
    @PostMapping
    public R register(@RequestBody User userRequest){
        User user = JsonUtil.getJsonToBean(userRequest, User.class);
        return userService.register(user)?R.success():R.error("新增失败，用户名已存在");
    }

    @ApiOperation(value = "更新")
    @PutMapping("/{id}")
    public R update(@PathVariable String id,@RequestBody User userRequest){
        User user = JsonUtil.getJsonToBean(userRequest,User.class);
        return userService.update(id,user) ? R.success() : R.error();
    }
}
